import numpy as np
import matplotlib.pyplot as plt
import random as rd
x=np.array(range(1, 10), float)
y=np.array(x*5+4, float)
for i in range(len(y)):
y[i]+=rd.random()-0.5+0.1
a=rd.random()
b=rd.random()
alpha=0.0001
h=1e-3
tolerence=1e-8
print("initial state\na: ", a, "b: ", b, sep="")
def reg(a, b):
global x
return a+b*x
def d_chi_sq(f, a, b, sigma=1.):
global y
return np.sum(((y-f(a, b))/sigma)**2)
dc_da=1; dc_db=1
while(abs(dc_da)>tolerence or abs(dc_db)>tolerence):
dc_da=(d_chi_sq(reg, a+h, b, sigma=1.)-d_chi_sq(reg, a-h, b, sigma=1.))/(2*h)
dc_db=(d_chi_sq(reg, a, b+h, sigma=1.)-d_chi_sq(reg, a, b-h, sigma=1.))/(2*h)
a-=alpha*dc_da
b-=alpha*dc_db
print("after DG\na: ", a, " b: ", b, sep="")
plt.plot(x, y, 'ro')
yy=a+b*x
plt.plot(x, yy)
plt.show()